package com.chunxuan.langquan.ui.activity;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.PixelFormat;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;

import com.chunxuan.langquan.R;
import com.chunxuan.langquan.base.Base2Activity;
import com.chunxuan.langquan.base.BaseResult2;
import com.chunxuan.langquan.base.Config;
import com.chunxuan.langquan.base.Global;
import com.chunxuan.langquan.dao.bean.CityEntity;
import com.chunxuan.langquan.dao.bean.LqProvinceBean;
import com.chunxuan.langquan.dao.http.APIRetrofit;
import com.chunxuan.langquan.support.util.ActiviceCollector;
import com.chunxuan.langquan.support.util.PinYinUtil;
import com.chunxuan.langquan.support.util.ToastUtilsLocal;
import com.chunxuan.langquan.support.view.LetterListView;
import com.chunxuan.langquan.ui.binding.Bind;
import com.chunxuan.langquan.ui.binding.ViewBinder;
import com.ruitu.arad.Arad;
import com.ruitu.arad.api.RxUtil;
import com.ruitu.arad.util.ToastUtils;

import java.io.Serializable;
import java.text.Collator;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;

import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Consumer;

public class SelectProvinceActivity extends Base2Activity implements AbsListView.OnScrollListener {

    //文件名称
    private final static String CityFileName = "allcity.json";

    @Bind(R.id.total_city_lv)
    private ListView totalCityLv;
    @Bind(R.id.total_city_letters_lv)
    private LetterListView lettersLv;
    @Bind(R.id.search_city_lv)
    private ListView searchCityLv;
    @Bind(R.id.no_search_result_tv)
    private TextView noSearchDataTv;

    private Handler handler;
    private TextView overlay; // 对话框首字母TextView
    private OverlayThread overlayThread; // 显示首字母对话框
    private boolean mReady = false;
    private boolean isScroll = false;

    private HashMap<String, Integer> alphaIndexer;// 存放存在的汉语拼音首字母和与之对应的列表位置

    //    protected List<CityEntity> hotCityList = new ArrayList<>();
    protected List<CityEntity> totalCityList = new ArrayList<>();
    protected List<CityEntity> curCityList = new ArrayList<>();
    protected List<CityEntity> searchCityList = new ArrayList<>();
    protected CityListAdapter cityListAdapter;
    protected SearchCityListAdapter searchCityListAdapter;

    private TextView tvCurrentCity,tvCityText;

    private String locationCity, curSelCity;
    private List<LqProvinceBean> lqProvinceBeanList=new ArrayList<>();
    private List<LqProvinceBean> lqCityList=new ArrayList<>();
    private List<LqProvinceBean> lqAreaList=new ArrayList<>();
    private String from;
    @Override
    protected int getLayoutRes() {
        return R.layout.activity_select_city;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ActiviceCollector.addActivity(this);
        // 默认软键盘不弹出
        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
        setSystemBarTransparent();
        setHeadTitle("选择省份");
        Intent intent=getIntent();
        if(null!=intent){
            Bundle bundle = intent.getExtras();
            lqProvinceBeanList= (List<LqProvinceBean>) bundle.getSerializable("lqProvinceBeanList");
            from=bundle.getString("from");
        }
        initView();
        initData();
        initListener();
    }

    private void initView() {
        ViewBinder.bind(this);
        tvCurrentCity=findViewById(R.id.cur_city_name_tv);
        tvCityText=findViewById(R.id.tv_current_city_text);
        handler = new Handler();
        overlayThread = new OverlayThread();
        searchCityListAdapter = new SearchCityListAdapter(this, searchCityList);
        searchCityLv.setAdapter(searchCityListAdapter);
//        locationCity = "杭州";
        String province= Arad.preferences.getString(Config.PROVINCE);
        String city= Arad.preferences.getString(Config.CITY);
        String area= Arad.preferences.getString(Config.AREA);
        if(!TextUtils.isEmpty(province)&&!TextUtils.isEmpty(city)&&!TextUtils.isEmpty(area)){
            locationCity=province+city+area;
        }else {
            locationCity="定位中";
        }
        tvCurrentCity.setText(locationCity);
        curSelCity = locationCity;
    }

    private void initData() {
        initTotalCityList();
        cityListAdapter = new CityListAdapter(this, totalCityList);
        totalCityLv.setAdapter(cityListAdapter);
        totalCityLv.setOnScrollListener(this);
        totalCityLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                if (position >=0) {
                    CityEntity cityEntity = totalCityList.get(position);
                    getCityByProvId(totalCityList.get(position).getId());
//                    showSetCityDialog(cityEntity.getName(), cityEntity.getCityCode());
                    curSelCity=cityEntity.getName();
                    if(null!=curSelCity&&curSelCity.length()>5){
                        tvCurrentCity.setTextSize(12);
                        tvCityText.setTextSize(8);
                    }else{
                        tvCurrentCity.setTextSize(20);
                        tvCityText.setTextSize(10);
                    }
//                    tvCurrentCity.setText(curSelCity);
                }

            }
        });
        lettersLv.setOnTouchingLetterChangedListener(new LetterListViewListener());
        initOverlay();
    }

    private Disposable getCityByProvId(int prov_id) {
        return APIRetrofit.getDefault().getCityByProvId(Global.HEADER,prov_id)
                .compose(RxUtil.<BaseResult2<List<LqProvinceBean>>>subIoObMain())
                .subscribe(new Consumer<BaseResult2<List<LqProvinceBean>>>() {
                    @Override
                    public void accept(BaseResult2<List<LqProvinceBean>> result2) throws Exception {
//                        hideProgress();
                        if(result2.isSuccess()){
                            lqCityList=result2.getData();
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("lqCityList", (Serializable) lqCityList);
                            bundle.putString("from",from);
                            Intent intent = new Intent(SelectProvinceActivity.this, SelectCityActivity.class);
                            intent.putExtras(bundle);
                            startActivity(intent);
                        }else{
                            ToastUtils.showShort(result2.getMsg());
                        }
                    }
                }, new Consumer<Throwable>() {
                    @Override
                    public void accept(Throwable throwable) throws Exception {
//                        hideProgress();
                        throwable.printStackTrace();
                        ToastUtils.showShort("获取城市列表失败");
                    }
                });
    }

    private void initListener() {

        searchCityLv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                CityEntity cityEntity = searchCityList.get(position);
                getCityByProvId(totalCityList.get(position).getId());
//                    showSetCityDialog(cityEntity.getName(), cityEntity.getCityCode());
                curSelCity=cityEntity.getName();
                if(null!=curSelCity&&curSelCity.length()>5){
                    tvCurrentCity.setTextSize(12);
                    tvCityText.setTextSize(8);
                }else{
                    tvCurrentCity.setTextSize(20);
                    tvCityText.setTextSize(10);
                }
//                tvCurrentCity.setText(curSelCity);
            }
        });
    }
    /**
     * 初始化全部城市列表
     */
    public void initTotalCityList() {
        totalCityList.clear();
        curCityList.clear();
        if(null!=lqProvinceBeanList&&lqProvinceBeanList.size()>0){
            lqProvinceBeanList=sort(lqProvinceBeanList);
            for(int m=0;m<lqProvinceBeanList.size();m++){
                if(TextUtils.isEmpty(lqProvinceBeanList.get(m).getFirst())){
                    String first= PinYinUtil.first(lqProvinceBeanList.get(m).getName());
                    lqProvinceBeanList.get(m).setFirst(first);
                }
                String name = lqProvinceBeanList.get(m).getName();
                String key = lqProvinceBeanList.get(m).getFirst();
                String pinyin = lqProvinceBeanList.get(m).getPinyin();
                String first = lqProvinceBeanList.get(m).getPinyin();
                String cityCode = lqProvinceBeanList.get(m).getCode();
                int id=lqProvinceBeanList.get(m).getId();
                String mergename=lqProvinceBeanList.get(m).getMergename();

                CityEntity cityEntity = new CityEntity();
                cityEntity.setName(name);
                cityEntity.setKey(key);
                cityEntity.setPinyin(pinyin);
                cityEntity.setFirst(first);
                cityEntity.setCityCode(cityCode);
                cityEntity.setId(id);
                cityEntity.setMergename(mergename);

                if (!cityEntity.getKey().equals("0") && !cityEntity.getKey().equals("1")) {
                    curCityList.add(cityEntity);
                }
                totalCityList.add(cityEntity);
            }
        }
    }
    public static List<LqProvinceBean> sort(List<LqProvinceBean> lqProvinceBeanList){
        // 获取中文环境
        Comparator comparator = Collator.getInstance(Locale.CHINA);
        // 排序实现
        Collections.sort(lqProvinceBeanList, (e1, e2) -> {
            return comparator.compare(e1.getName(), e2.getName());
        });
        // java8打印排序后的结果
//        lqProvinceBeanList.stream().forEach(System.out::println);
        return lqProvinceBeanList;
    }
    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {
        if (scrollState == SCROLL_STATE_TOUCH_SCROLL
                || scrollState == SCROLL_STATE_FLING) {
            isScroll = true;
        } else {
            isScroll = false;
        }
    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem,
                         int visibleItemCount, int totalItemCount) {
        if (!isScroll) {
            return;
        }

        if (mReady) {
            String key = getAlpha(totalCityList.get(firstVisibleItem).getKey());
            overlay.setText(key);
            overlay.setVisibility(View.VISIBLE);
            handler.removeCallbacks(overlayThread);
            // 延迟让overlay为不可见
            handler.postDelayed(overlayThread, 700);
        }
    }

    /**
     * 总城市适配器
     */
    private class CityListAdapter extends BaseAdapter {
        private Context context;

        private List<CityEntity> totalCityList;
        //        private List<CityEntity> hotCityList;
        private LayoutInflater inflater;
        final int VIEW_TYPE = 3;

        CityListAdapter(Context context,
                        List<CityEntity> totalCityList) {
            this.context = context;
            this.totalCityList = totalCityList;
//            this.hotCityList = hotCityList;
            inflater = LayoutInflater.from(context);

            alphaIndexer = new HashMap<>();

            for (int i = 0; i < totalCityList.size(); i++) {
                // 当前汉语拼音首字母
                String currentStr = totalCityList.get(i).getKey();

                String previewStr = (i - 1) >= 0 ? totalCityList.get(i - 1).getKey() : " ";
                if (!previewStr.equals(currentStr)) {
                    String name = getAlpha(currentStr);
                    alphaIndexer.put(name, i);
                }
            }
        }

        @Override
        public int getViewTypeCount() {
            return VIEW_TYPE;
        }

        @Override
        public int getItemViewType(int position) {
            return position < 2 ? position : 2;
        }

        @Override
        public int getCount() {
            return totalCityList == null ? 0 : totalCityList.size();
        }

        @Override
        public Object getItem(int position) {
            return totalCityList.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            int viewType = getItemViewType(position);
                if (null == convertView) {
                    holder = new ViewHolder();
                    convertView = inflater.inflate(R.layout.city_list_item_layout, null);
                    ViewBinder.bind(holder, convertView);
                    convertView.setTag(holder);
                } else {
                    holder = (ViewHolder) convertView.getTag();
                }

                CityEntity cityEntity = totalCityList.get(position);
                holder.cityKeyTv.setVisibility(View.VISIBLE);
                holder.cityKeyTv.setText(getAlpha(cityEntity.getKey()));
                holder.cityNameTv.setText(cityEntity.getName());

                if (position >= 1) {
                    CityEntity preCity = totalCityList.get(position - 1);
                    if (preCity.getKey().equals(cityEntity.getKey())) {
                        holder.cityKeyTv.setVisibility(View.GONE);
                    } else {
                        holder.cityKeyTv.setVisibility(View.VISIBLE);
                    }
                }

            return convertView;
        }

        private class ViewHolder {
            @Bind(R.id.city_name_tv)
            TextView cityNameTv;
            @Bind(R.id.city_key_tv)
            TextView cityKeyTv;
        }
    }


    /**
     * 搜索城市列表适配器
     */
    private class SearchCityListAdapter extends BaseAdapter {

        private List<CityEntity> cityEntities;
        private LayoutInflater inflater;

        SearchCityListAdapter(Context mContext, List<CityEntity> cityEntities) {
            this.cityEntities = cityEntities;
            inflater = LayoutInflater.from(mContext);
        }

        @Override
        public int getCount() {
            return cityEntities == null ? 0 : cityEntities.size();
        }

        @Override
        public Object getItem(int position) {
            return cityEntities.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            if (null == convertView) {
                holder = new ViewHolder();
                convertView = inflater.inflate(R.layout.city_list_item_layout, null);
                ViewBinder.bind(holder, convertView);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }

            CityEntity cityEntity = cityEntities.get(position);
            holder.cityKeyTv.setVisibility(View.GONE);
            holder.cityNameTv.setText(cityEntity.getName());

            return convertView;
        }


        private class ViewHolder {
            @Bind(R.id.city_name_tv)
            TextView cityNameTv;
            @Bind(R.id.city_key_tv)
            TextView cityKeyTv;
        }
    }

    /**
     * 获得首字母
     */
    private String getAlpha(String key) {
        if (key.equals("0")) {
            return "定位";
        } else {
            return key;
        }
    }


    /**
     * 初始化汉语拼音首字母弹出提示框
     */
    private void initOverlay() {
        mReady = true;
        LayoutInflater inflater = LayoutInflater.from(this);
        overlay = (TextView) inflater.inflate(R.layout.overlay, null);
        overlay.setVisibility(View.INVISIBLE);
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                        | WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,
                PixelFormat.TRANSLUCENT);
        WindowManager windowManager = (WindowManager) this
                .getSystemService(Context.WINDOW_SERVICE);
        windowManager.addView(overlay, lp);
    }


    private class LetterListViewListener implements
            LetterListView.OnTouchingLetterChangedListener {

        @Override
        public void onTouchingLetterChanged(final String s) {
            isScroll = false;
            if (alphaIndexer.get(s) != null) {
                int position = alphaIndexer.get(s);
                totalCityLv.setSelection(position);
                overlay.setText(s);
                overlay.setVisibility(View.VISIBLE);
                handler.removeCallbacks(overlayThread);
                // 延迟让overlay为不可见
                handler.postDelayed(overlayThread, 700);
            }
        }
    }

    /**
     * 设置overlay不可见
     */
    private class OverlayThread implements Runnable {
        @Override
        public void run() {
            overlay.setVisibility(View.GONE);
        }
    }

    /**
     * 隐藏软件盘
     */
    public void hideSoftInput(IBinder token) {
        if (token != null) {
            InputMethodManager im = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            im.hideSoftInputFromWindow(token,
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }


    /**
     * 设置沉浸式状态栏
     */
    private void setSystemBarTransparent() {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            // 5.0 LOLLIPOP解决方案
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            getWindow().setStatusBarColor(Color.TRANSPARENT);
        } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            // 4.4 KITKAT解决方案
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        }
    }
}
